package main

import (
	"context"
	"fmt"
	"go-grpc/service"
	"go-grpc/token/service/impl"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/grpclog"
	"log"
	"time"
)

const (
	// Address gRPC服务地址
	Address = "127.0.0.1:8003"
)

func main() {
	//1、声明一个放注册配置的切片
	var opts []grpc.DialOption

	//2、声明一个user
	user := &impl.Authentication{
		User:     "admin",
		Password: "admin",
	}

	//3、往客户端里注册各种配置，比如：拦截认证、请求日志
	opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))

	opts = append(opts, grpc.WithPerRPCCredentials(user))

	opts = append(opts, grpc.WithUnaryInterceptor(interceptor))

	//4、 建立连接，加入注册的配置
	conn, err := grpc.Dial(Address, opts...)

	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()

	request := &service.ReqParam{
		Id:   123,
		Name: "西木",
	}

	// 5. 调用 hello_grpc.pb.go 中的NewQueryUserClient方法建立客户端
	query := service.NewQueryUserClient(conn)

	//6、调用rpc方法
	res, err := query.GetUserInfo(context.Background(), request)

	if err != nil {
		log.Fatal("调用gRPC方法错误: ", err)
	}
	fmt.Println("拦截器：调用gRPC方法成功，ProdStock = ", res)

}

// interceptor 客户端拦截器
func interceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
	start := time.Now()
	err := invoker(ctx, method, req, reply, cc, opts...)
	grpclog.Printf("method=%s req=%v rep=%v duration=%s error=%v\n", method, req, reply, time.Since(start), err)
	return err
}
